package twilight.companion.event;

import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.event.level.ExplosionEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import twilight.companion.TwilightCompanion;
import twilight.companion.init.ModItems;

@Mod.EventBusSubscriber(modid = TwilightCompanion.MOD_ID)
public class TwilightContractEvents {

    @SubscribeEvent
    public static void onItemEntitySpawn(EntityJoinLevelEvent event) {
        if (event.getEntity() instanceof ItemEntity itemEntity) {
            ItemStack stack = itemEntity.getItem();
            if (stack.is(ModItems.TWILIGHT_CONTRACT.get())) {
                itemEntity.setUnlimitedLifetime();
                itemEntity.setInvulnerable(true);
            }
        }
    }

    @SubscribeEvent
    public static void onItemToss(ItemTossEvent event) {
        ItemStack stack = event.getEntity().getItem();
        if (stack.is(ModItems.TWILIGHT_CONTRACT.get())) {
            ItemEntity itemEntity = event.getEntity();
            
            itemEntity.setPickUpDelay(5);

            itemEntity.setDeltaMovement(
                itemEntity.getDeltaMovement().x * 0.3,
                itemEntity.getDeltaMovement().y * 0.5,
                itemEntity.getDeltaMovement().z * 0.3
            );
        }
    }

    @SubscribeEvent
    public static void onExplosion(ExplosionEvent.Detonate event) {
        event.getAffectedEntities().removeIf(entity -> {
            if (entity instanceof ItemEntity itemEntity) {
                ItemStack stack = itemEntity.getItem();
                return stack.is(ModItems.TWILIGHT_CONTRACT.get());
            }
            return false;
        });
    }

    @SubscribeEvent
    public static void onLivingDrops(LivingDropsEvent event) {
        for (ItemEntity itemEntity : event.getDrops()) {
            ItemStack stack = itemEntity.getItem();
            if (stack.is(ModItems.TWILIGHT_CONTRACT.get())) {
                itemEntity.setUnlimitedLifetime();
                itemEntity.setInvulnerable(true);
            }
        }
    }
}